// TODO
//$(function () { this.Init(); });

var _storeDetailInfo = null;
var _currentloginuser = null;
var _storeid = 0;
function plusReady() {
    Init();
}

if (window.plus) {
    plusReady();
} else {
    document.addEventListener('plusready', plusReady, false);
}

function Init() {
    _storeid = getUrlParam("storeid");
    _currentloginuser = JSON.parse(plus.storage.getItem(storageManager.user));

    //店铺详情
    PaintPage();

    //团购商品取出50条，带店铺信息
    var requestdata = { "store": _storeid, "type": "groupbuy,presell,normal", group: 1, "onlysell": 1, "limit": 50, "page": 1 };
    //console.log(JSON.stringify(requestdata));
    $.ajax({
        type	: "GET",
        url		: configManager.RequstUrl + "api/goods/list",
        async	: true,
        data	: requestdata
    }).done(function (data) {
        if ("success" != data.state) { console.log(data.message); return false; }
        var goods = data.data;
        //商家的团购商品
        if (goods.groupbuy && goods.groupbuy.length > 0) {
            PaintDisCountProudct(goods.groupbuy);
        }

        // 预售商品
        if (goods.presell && goods.presell.length > 0) {
            PaintPreSellProudct(goods.presell);
        }

        // 普通商品
        if (goods.normal && goods.normal.length > 0) {
            PaintProductList(goods.normal);
        }

    }).fail(function () {
        plus.nativeUI.alert(errorMessage.interface);
    });

    BindEvent();
    IsCollecteShop();
}

// 店铺详情
function PaintPage() {
    $.ajax({
        type: 'Get',
        url: configManager.RequstUrl + "api/store/info?store=" + _storeid
    }).done(function (data) {
        if (data.state != "success") { console.log(data.message); return; }
        var shopbaseinfo = data.data;
        _storeDetailInfo = shopbaseinfo;

        var html = [];
        // 商铺图片
        html.push("<div class='sjqbgdtu' style='width:398px;height:212px'>");
        html.push("<a><img width=\"398\" height=\"212\" src='" + configManager.storeImgurl.format(shopbaseinfo.store_pic, "500-300") + "' /></a>");
        html.push("</div>");
        html.push("<div class='sjxqtpswz'>" + shopbaseinfo.store_name + "</div>");
        $("#storepic").html(html.join(""));
        html = [];

        // 营业时间
        html.push("<div  class='grxinxis'>");
        html.push("<p class='sjxqbddd'><span><a href='tel:" + shopbaseinfo.store_phone + "'><i class=\"phone sign icon\" style='font-size:3.2em; color: green;left:1.0em'></i></a></span><b>" + shopbaseinfo.store_address + "</b></p>");
        html.push("<p class='sjxqyysj'>营业时间：" + shopbaseinfo.store_hours + "</p>");
        html.push("</div>");

        // 优惠买单
        html.push("<div class='grxinxis'>");

        html.push("<p class='sjxqmdkxyh'><span style='display:none'><a id='buynow'>买单</a></span><b><img src='../../images/sjxqtu3.png' /></b>买单可享优惠</p>");

        html.push("<p class='sjxqxffl'>普通支付返利" + shopbaseinfo.offline_pay_fee + "%<br />   金币支付奖利" + shopbaseinfo.offline_pay_fee + "%  </p>");
        html.push("</div>");

        // 商铺介绍
        html.push("<div class='sjxqbkbg'>");
        html.push("<h2>店铺介绍</h2>");
        html.push("<p>" + shopbaseinfo.store_intro + "</p>");
        html.push("<p class='sjxqsst'>");
        if (shopbaseinfo.is_refund == 1) {
            html.push("<span><i class=\"checked checkbox icon\"></i>随时退</span>");
        }
        if (shopbaseinfo.is_noreserve == 1) {
            html.push("<span><i class=\"checked checkbox icon\"></i>免预约</span>");
        }
        if (shopbaseinfo.is_takeaway == 1) {
            html.push("<span><i class=\"checked checkbox icon\"></i>外送</span>");
        }
        html.push("</p>");

        html.push("</div>");
        html.push("<div class='sjxqbkbg'>");
        html.push("<p class='sjxqsjpf'><span>商家评分 (" + shopbaseinfo.store_score + ") <i style='display:none;' class=\"angle right icon\"></i></span>" + DrawScore(shopbaseinfo.store_score) + "</p>");
        html.push("</div>");
        $("#storebaseInfo").html(html.join(""));

        //点击买单跳转到支付二维码
        $("#storebaseInfo").on("click", "#buynow", function () {
            if (!_currentloginuser) {
                clicked('../account/login.html', false, false, 'slide-in-bottom');
                return;
            }
            if (_currentloginuser.id == shopbaseinfo.user_id) {
                plus.ui.alert("不能给自己买单", function () { }, configManager.alerttip, configManager.alertCtip);
            } else {
                clicked('../payment/direct.html?code=' + shopbaseinfo.code);
            }
        });

    });


}

// 团购产品
function PaintDisCountProudct(goodslist) {
    var html = [];
    html.push('<h2 class="sjxqtgxqbt"><a href="#">本店团购</a></h2>');
    var divclass = "";
    $.each(goodslist, function (i, goods) {
        //商品图片
        if (0 == i) { divclass = "discountgoods firstgoods"; } else { divclass = "discountgoods othergoods"; }
        html.push('<div style="border-bottom:1px solid #ddd" class="' + divclass + '" tip="' + goods.id + '">')
        html.push('<dl style="border:none"><a href="#">');
        html.push('<dt style="width:27%"><p class="sjxqyhcptu"><img style="width:70px;height:70px; border:1px solid #ddd; padding:2px" width="70" height="70" src="' + configManager.goodsImgurl.format(goods.pic, "150-150") + '"></p></dt>');
        html.push('<dd style="margin-top:1em; width: 73%; line-height:1.2em">' + goods.title + '</dd><dd><b class="zcd" style="font-size:1.2em">' + goods.price + '</b>元<font>' + goods.market_price + '元</font></dd>');
        html.push('<dd style="line-height:1.2em; font-size:0.8em;">');
        if (goods.any_time_refund == 1) {
            html.push("<span><i class=\"checked checkbox icon\"></i>随时退</span>&nbsp;&nbsp;&nbsp;");
        }
        if (goods.over_time_refund == 1) {
            html.push("<span><i class=\"checked checkbox icon\"></i>过期退</span>&nbsp;&nbsp;&nbsp;");
        }
        html.push("<span><i class=\"truck icon\"></i>已售 " + goods.selled + " 件</span>");

        html.push('</a></dd></dl>');
        if (i == 0) {
            html.push('<p style="text-indent:2em; border-top:1px dashed #ddd; color:#777">' + goods.content.substr(0, 40) + '...</p>');
            html.push('<p><span><b>总价值</b>' + goods.market_price + '元</span></p>');
            html.push('<p><span><b>团购价</b><span style="color:#f30; font-size:1.2em">' + goods.price + '元</span></span></p>');
        }
        html.push('</div>');

    });
    html.push('<div id="showallgoods"><p class="sjxqtw"><a><span class="tghandler"><i class=\"angle down icon\"></i></span><span class="title">查看所有团购商品...</span></a> </p></div>');

    $("#groupbuying").html(html.join(""));
    $("#groupbuying").show();
}
// 预售产品
function PaintPreSellProudct(goodslist) {
    var html = [];
    html.push('<h2 class="sjxqtgxqbt"><a href="#">本店预售</a></h2>');
    var divclass = "";
    $.each(goodslist, function (i, goods) {
        //商品图片
        if (0 == i) { divclass = "discountgoods firstgoods"; } else { divclass = "discountgoods othergoods"; }
        html.push('<div style="border-bottom:1px solid #ddd" class="' + divclass + '" tip="' + goods.id + '">')
        html.push('<dl style="border:none"><a href="#">');
        html.push('<dt style="width:27%"><p class="sjxqyhcptu"><img style="width:70px;height:70px; border:1px solid #ddd; padding:2px" width="70" height="70" src="' + configManager.goodsImgurl.format(goods.pic, "150-150") + '"></p></dt>');
        html.push('<dd style="margin-top:1em; width: 73%; line-height:1.2em">' + goods.title + '</dd><dd><b class="zcd" style="font-size:1.2em">' + goods.price + '</b>元<font>' + goods.market_price + '元</font></dd>');
        html.push('<dd style="line-height:1.2em; font-size:0.8em;">');
        html.push("<span><i class=\"truck icon\"></i>已售 " + goods.selled + " 件</span>");

        html.push('</a></dd></dl>');
        html.push('</div>');

    });
    html.push('<div id="showallpresellgoods"><p class="sjxqtw"><a><span class="tghandler"><i class=\"angle down icon\"></i></span><span class="title">查看所有预售商品...</span></a> </p></div>');

    $("#presellgoodslist").html(html.join(""));
    $("#presellgoodslist").show();
}


// 产品详情
function PaintProductList(goodslist) {
    var html = [];
    $.each(goodslist, function (i, goods) {
        //商品信息
        var goodsinfo = [goods.id, goods.store_id, goods.title, goods.price, goods.pic];
        html.push("<div style='margin:4px 0px; padding:5px 15px; background:#fff;box-shadow:0 2px 2px #ddd;' tip=" + goodsinfo.join("|") + ">");
        html.push("<div style='float:left; width:25%;'><img width='50' height='50' style='width:50px; height: 50px; border:1px solid #ddd; padding:2px;' src='" + configManager.goodsImgurl.format(goods.pic, "100-100") + "'' alt='' /></div>");
        html.push("<div style='float:left; width:75%'><p style='font-size:1.3em; color:#555; width:100%; line-height:1.5em;'><span style='float:right; font-size:0.8em; color:green;'><i class=\"truck icon\"></i>已售：" + goods.selled + "件</span>" + goods.title + "</p>");
        html.push("<p style='line-height:1.8em; margin-top:0.7em;'><span style='background:#f60; display:inline-block; float:right; padding:0.3em; font-size:0.8em; height:1.3em; line-height:1.3em; border-radius:2px; color:#fff; font-size:1em' name='buy'  tip=" + goodsinfo.join("|") + "><i class=\"cart icon\" style='opacity:1'></i>购买</span><span style='font-size:1.2em;color:#f60'>￥" + goods.price + " &nbsp;&nbsp;&nbsp; <span style='color:#777; font-size:0.8em; text-decoration:line-through'>￥" + goods.market_price + "</span></p>");
        html.push("</div>");
        html.push("<br style='clear:both'></div>");
    });

    $("#goodsitemlist").html(html.join(""));
}

// TODO
function BindEvent(user) {
    // 分享
    $("#sharepop").on("click", function () { $(this).hide(); });
    $("#btnshare").on("click", function () {
        $("#sharepop").show();
    });

    // weixin: 0  weixinquan:1  inaweibo:2  tencentweibo:3  QQ: 4
    $("li[name=shareitem]").on("click", function () {
        var item = $(this).attr("tip");
        ShareBarCode(item);
    });

    // 关注、收藏
    $("#btncollect").on("click", function () {
        if (!_currentloginuser) {
            clicked('../account/login.html', false, false, 'slide-in-bottom');
            return;
        } else {
            var iscancle = $(this).attr("tip") == "1" ? true : false;

            // 更改关注按钮样式
            if (iscancle) {
                $("#btncollect i").addClass('empty');
                $("#btncollect").attr("tip", "0");
            } else {
                $("#btncollect i").removeClass('empty');
                $("#btncollect").attr("tip", "1");
            }

            // 是否关注
            CollecteShop(iscancle);
        }
    });

    // 回退
    $("#back").on("click", function () {
        plus.webview.getWebviewById(pageName.main).evalJS("gohome()");
    });

    // 跳转购物车页面
    $("#goodsitemlist").on("click", "span[name=buy]", function () {
        //临时订单
        console.log("1");
        var goodsinfo = $(this).attr("tip").split("|");
        var currentgoods = {
            "id": goodsinfo[0],
            "storeid": goodsinfo[1],
            "title": goodsinfo[2],
            "price": goodsinfo[3],
            "pic": goodsinfo[4],
            "count": 1,
            "selected": true
        };
        var mycart = JSON.parse(plus.storage.getItem(storageManager.cart));
        if (!mycart) { mycart = []; }
        // 如果不是本商店商品，清空购物车
        $.each(mycart, function () {
            var goods = this;
            if (goods && goods.storeid != currentgoods.storeid) {
                plus.storage.removeItem(storageManager.cart);
            }
        });
        // 更新购物车
        var existsIndex = -1;
        $.each(mycart, function (index, goods) { if (goods && goods.id == currentgoods.id) { existsIndex = index; return false; } })
        if (existsIndex < 0) {
            mycart.push(currentgoods);
        } else {
            mycart[existsIndex].count = mycart[existsIndex].count + 1;
            mycart[existsIndex].price = currentgoods.price;
        }

        // 放入缓存，购物车，提交订单需要
        plus.storage.setItem(storageManager.cart, JSON.stringify(mycart));
        clicked("../mine/order/cart.html", false, false, "pop-in");
        return false;
    });


    // 跳转商品详情
    $("#groupbuying").on("click", "div.discountgoods", function () {
        var page = '../mine/goods/detail.html?goodsid=' + $(this).attr("tip");
        console.log(page);
        clicked(page, false, false, "pop-in");
    });

    //显示隐藏其他团购商品
    $("#groupbuying").on("click", "#showallgoods", function () {
        if ($(this).find(".title").html() != "收起") {
            $(this).find(".title").html("收起");
            $(this).find('.tghandler').find('i').removeClass('down').addClass('up');
            $(".othergoods").slideDown(1000);
        } else {
            $(this).find(".title").html("查看所有团购商品...");
            $(this).find('.tghandler').find('i').removeClass('up').addClass('down');
            $(".othergoods").slideUp(500);
        }
    });

    // 跳转商品详情
    $("#presellgoodslist").on("click", "div.discountgoods", function () {
        var page = '../mine/goods/detail.html?goodsid=' + $(this).attr("tip");
        console.log(page);
        clicked(page, false, false, "pop-in");
    });
    // 预售商品
    $("#presellgoodslist").on("click", "#showallpresellgoods", function () {
        if ($(this).find(".title").html() != "收起") {
            $(this).find(".title").html("收起");
            $(this).find('.tghandler').find('i').removeClass('down').addClass('up');
            $(".othergoods").slideDown(1000);
        } else {
            $(this).find(".title").html("查看所有预售商品...");
            $(this).find('.tghandler').find('i').removeClass('up').addClass('down');
            $(".othergoods").slideUp(500);
        }
    });


}

// 是否收藏
function IsCollecteShop() {
    if (undefined != _currentloginuser && null != _currentloginuser) {
        $.ajax({
            type: 'POST',
            url: configManager.RequstUrl + "api/store/iscollect",
            data: { "userid": _currentloginuser.id, "store": _storeid, "token": _currentloginuser.token }
        }).done(function (data) {
            if (data.state != "success") { console.log(data.message); return; }
            if (data.iscollect) {
                $("#btncollect i").removeClass('empty');
                $("#btncollect").attr("tip", "1");
            }
        });
    }
}

// 关注/取消关注店铺
function CollecteShop(iscancle) {
    console.log(iscancle);
    // 关注商家
    var requsturl = (iscancle ? "api/store/delcollect" : "api/store/collection");
    console.log(requsturl);
    $.ajax({
        type: 'POST',
        url: configManager.RequstUrl + requsturl,
        data: { "userid": _currentloginuser.id, "store": _storeid, "token": _currentloginuser.token }
    }).done(function (data) {
        if (data.state != "success") { console.log(data.message); return; }

    });
}

function DrawScore(score) {
    var pic = '0';
    if (score > 1 && score < 2) {
        pic = '1';
    } else if (score > 2 && score < 3) {
        pic = '2';
    } else if (score == 3) {
        pic = '3';
    } else if (score > 3 && score < 4) {
        pic = '35';
    } else if (score == 4) {
        pic = '4';
    } else if (score > 4 && score < 5) {
        pic = '45';
    } else if (score == 5) {
        pic = '5';
    } else {
        pic = '0';
    }
    return '<img style="vertical-align:middle; margin-top:5px" width="90" height="18" src="http://i3.dpfile.com/s/i/app/api/32_' + pic + 'star.png" />';
}

// TODO
// 生产用户唯一标识二维码
function ShareBarCode(item) {
    // 获取二维码
    $.ajax({
        type: 'Get',
        async: false,
        url: configManager.RequstUrl + 'api/common/qrcode?type=login&code=' + _storeDetailInfo.code
    }).done(function (data) {
        if (data.state != "success") {
            console.log(data.message);
            return;
        }
        var httpurl = data.uri;
        var filename = plus.io.PUBLIC_DOWNLOADS + "/" + getUrlFileName(data.uri);

        // 判断本地是否存在该图片
        try {
            plus.io.resolveLocalFileSystemURL(filename, function (entry) {
                shareShow(data.link, filename, item);
            }, function (e) {
                DownLoadFile(httpurl, filename, item, data.link);
            });
        } catch (err) {
            DownLoadFile(httpurl, filename, item, data.link);
        }
    });
}

function DownLoadFile(httpurl, filename, item, link) {
    // 下载图片到本地，成功后分享
    var dtask = plus.downloader.createDownload(httpurl, { filename: filename }, function (d, status) {
        // 下载完成
        if (status == 200) {
            shareShow(link, d.filename, item);
        } else {
            shareShow(link, null, item);
        }
    });
    dtask.start();
}